<template>
  <div>
    <div class="tags-model-table tag-model-title">
      <div v-for="(item,index) in modelTitle" :key="index"
           :style="{width:modelWidth(index) + '%',textAlign:index === 1 || index === 5 ? 'left':'center'}">
        {{ item }}
      </div>
    </div>
    <div v-loading="loading">
      <!--新增-->
      <el-form :model="addList" :rules="rules" ref="addList">
        <div class="tags-model-table tag-model-title add-model" v-if="add">
          <div style="width:12%">
            <el-form-item prop="modelName" :rules="rules.modelName">
              <el-input size="mini" v-model="addList.modelName" style="height: 30px;width: 80%;margin: 0 auto;"
                        maxlength="100">
              </el-input>
            </el-form-item>
          </div>
          <div style="width:45%;display: flex">

            <div style="display: flex">
              <div v-for="(it,i) in addList.tagsSnapshot" :key="i" class="tagsStyle" v-if="isNamedGroup(it)"
              >
                {{ it.name }}
              </div>
            </div>
            <div class="add_set_tags" @click="setTagsSnapshot('add')">设置命名规则</div>
          </div>
          <div style="width:5%">
            <el-form-item prop="groupDiv" :rules="rules.groupDiv" class="tagsRules">
              <el-select size="mini" v-model="addList.groupDiv">
                <el-option v-for="item in divList" :key="item.value" :value="item.value"
                           :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="width:5%">
            <el-form-item prop="tagDiv" :rules="rules.tagDiv" class="tagsRules">
              <el-select size="mini" v-model="addList.tagDiv">
                <el-option v-for="item in divList" :key="item.value" :value="item.value"
                           :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="width:18%">
            <el-form-item prop="offerId" :rules="rules.offerId">
              <el-select size="mini" v-model="addList.offerId" filterable clearable @change="changeOfferID">
                <el-option v-for="item in offerList" :key="item.id" :value="item.id" :label="item.name"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="width:12%" class="systemMenu">
            <el-button size="mini" type="primary" @click="saveAdd">保存</el-button>
            <el-button size="mini" @click="cancelAdd">取消</el-button>
          </div>
        </div>
      </el-form>

      <!--列表-->
      <el-form :model="modelList" :rules="rules" ref="modelForm">
        <div v-for="(item,index) in modelList" :key="index" class="tags-model-table" :style="{backgroundColor:index % 2 === 0?'rgba(249, 249, 249, 100)':
     'rgba(255, 255, 255, 100)'}"
        >
          <!--         -->
          <div style="width:12%">
            <el-form-item :prop="index+'.modelName'" :rules="rules.modelName">
              <el-input size="mini" @blur="saveModel(index)" v-model="item.modelName" maxlength="100"
                        style="height: 30px;width: 80%;margin: 0 auto;">
              </el-input>
            </el-form-item>
          </div>
          <div style="width:45%;display: flex">
            <div>
              <div style="color: #f56c6c">{{ uploadError && index === uploadErrorIndex ? '请选择命名规则' : '' }}</div>
              <div style="display: flex">
                <div v-for="(it,i) in item.tagsSnapshot" :key="i" class="tagsStyle" v-if="isNamedGroup(it)"
                     :class="uploadError && index === uploadErrorIndex ? 'add-error-model':''">
                  {{ it.name }}
                </div>
              </div>
            </div>
          </div>
          <div style="width:5%">
            <el-form-item :prop="index+'.groupDiv'" :rules="rules.groupDiv" class="tagsRules">
              <el-select size="mini" v-model="item.groupDiv" @change="saveModel(index)">
                <el-option v-for="item in divList" :key="item.value" :value="item.value"
                           :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="width:5%">
            <el-form-item :prop="index+'.tagDiv'" :rules="rules.tagDiv" class="tagsRules">
              <el-select size="mini" v-model="item.tagDiv" @change="saveModel(index)">
                <el-option v-for="item in divList" :key="item.value" :value="item.value"
                           :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="width:18%">
            <el-form-item :prop="index+'.offerId'" :rules="rules.offerId">
              <el-select size="mini" v-model="item.offerId" filterable clearable @change="saveModel(index)">
                <el-option v-for="item in offerList" :key="item.id" :value="item.id" :label="item.name"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="width:12%" class="systemMenu">
            <i class="el-icon-setting" @click="setTagsSnapshot(index)"></i>
            <i class="el-icon-copy-document" @click="copyModel(index)"></i>
            <i class="el-icon-close" @click="deleteModel(index)"></i>
          </div>
        </div>
      </el-form>

    </div>
    <div class="block" style="margin-top: 1em;display: flex;justify-content: flex-end;margin-right: 1em;">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page="page.currentPage"
        :page-size="page.pageSize"
        :total="page.total"
        @current-change="changePage"
      >
      </el-pagination>
    </div>
    <div style="margin-top: 1em">
      <el-button size="mini" @click="addModel">添加模板</el-button>
    </div>
    <el-dialog class="ruleDialog" append-to-body :visible.sync="dialogVisible" :close-on-click-modal="false"
               :show-close="false"
               width="67%"
    >
      <creative-name-rule v-if="dialogVisible" :data-list="dataList" :model-index="modelIndex" :add-tags="addTags"
                          :cancel="closeDialog" ref="namingRules"></creative-name-rule>
    </el-dialog>
  </div>
</template>

<script>
import {getOfferIdList, submitModel, getPage, removeModel} from "@/api/system/creative_tags"
import {mapGetters} from "vuex";
import creativeNameRule from "@/views/system/components/tagsComponent/creativeNameRule";

export default {
  name: "tagsModel",
  components: {
    creativeNameRule
  },
  props: {
    offerId: String
  },
  data() {
    let checkTagDiv = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择同组分隔'))
      } else {
        if (String(rule.field).includes('.')) {
          if (this.modelList[rule.field.split('.')[0]].tagDiv === this.modelList[rule.field.split('.')[0]].groupDiv) {
            callback(new Error('组内分隔和同组分隔不可以使用相同分隔符!'))
          } else {
            callback()
          }
        } else {
          if (this.addList.tagDiv === this.addList.groupDiv) {
            callback(new Error('组内分隔和同组分隔不可以使用相同分隔符!'))
          } else {
            callback()
          }
        }
      }
    }
    let checkGroupDiv = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择组外分隔'))
      } else {
        if (rule.field.includes('.')) {
          if (this.modelList[rule.field.split('.')[0]].tagDiv === this.modelList[rule.field.split('.')[0]].groupDiv) {
            callback(new Error('组内分隔和同组分隔不可以使用相同分隔符!'))
          } else {
            callback()
          }
        } else {
          if (this.addList.tagDiv === this.addList.groupDiv) {
            callback(new Error('组内分隔和同组分隔不可以使用相同分隔符!'))
          } else {
            callback()
          }
        }
      }
    }
    return {
      uploadError: false,
      uploadErrorIndex: '',
      addError: false,
      add: false,
      addList: {
        tagDiv: '&',
        groupDiv: '-',
        offerId:'',
      },
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      modelTitle: ['模板名称', '命名规则', '组外分隔', '同组分隔', '关联订单', ''],
      modelList: [],
      divList: [
        {label: '-', value: '-'},
        {label: '_', value: '_'},
        {label: '、', value: '、'},
        {label: '/', value: '/'},
        {label: '&', value: '&'},
        {label: '~', value: '~'},
      ],
      offerList: [],
      dialogVisible: false,
      dataList: {},
      modelIndex: '',
      rules: {
        modelName: [{required: true, message: '请输入模板名称', trigger: 'blur'}],
        offerId: [{required: true, message: '请选择关联订单', trigger: 'change'}],
        tagDiv: [{required: true, validator: checkTagDiv, trigger: 'change'}],
        groupDiv: [{required: true, validator: checkGroupDiv, trigger: 'change'}],
      }

    }
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  mounted() {
    this.onLoad(this.page)
    getOfferIdList({statusList: '0,1,2,3'}).then(res => {
      this.offerList = res.data.data
    })
  },
  created() {
    if (this.offerId) {
      this.add = true
      this.addList.offerId = this.offerId
    }
  },
  watch:{
    offerId:{
      deep:true,
      handler(val){
        if(val){
          let self = this;
          self.add = true
          self.addList.offerId = val
        }
      }
    },
  },
  methods: {
    changeOfferID() {
      if (this.offerId) {
        this.$forceUpdate()
      }
    },
    changePage(v) {
      this.page.currentPage = v;
      this.onLoad(this.page)
    },
    modelWidth(i) {
      switch (i) {
        case 0:
          return 12
        case 1:
          return 45;
        case 2:
          return 5;
        case 3:
          return 5;
        case 4:
          return 18;
        case 5:
          return 12;
      }
    },
    //获取列表
    onLoad(page, params = {}) {
      this.loading = true
      getPage(page.currentPage, page.pageSize, Object.assign(params)).then(res => {
        let data = res.data.data
        data.records.map((item) => {
          item.tagsSnapshot = JSON.parse(item.tagsSnapshot)
        })
        this.modelList = data.records;
        this.page.total = data.total
        this.loading = false
      })
    },
    //设置规则
    setTagsSnapshot(i) {
      if (i === 'add') {
        this.dataList = this.addList;
        this.addError = this.addList && this.addList.length > 0
        this.modelIndex = 'add'
        this.dialogVisible = true
      } else {
        this.uploadError = this.modelList[i] && this.modelList[i].length > 0
        this.uploadErrorIndex = this.uploadError ? i : ''
        this.dataList = this.modelList[i]
        this.modelIndex = i
        this.dialogVisible = true
      }
    },
    //添加模板
    addModel() {
      this.addList = {
        tagDiv: '&',
        groupDiv: '-'
      }
      this.add = true;
    },
    //复制模板
    copyModel(i) {
      this.add = true;
      this.addList = {
        modelName: this.modelList[i].modelName,
        tagsSnapshot: this.modelList[i].tagsSnapshot,
        groupDiv: this.modelList[i].groupDiv,
        tagDiv: this.modelList[i].tagDiv,
      }
    },
    //删除模板
    deleteModel(i) {
      removeModel(this.modelList[i].id).then(res => {
        if (res.data.code === 200) {
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
          this.onLoad(this.page)
        }
      })
    },
    //关闭命名弹窗
    closeDialog() {
      this.dialogVisible = false
    },
    //更新模板
    saveModel(i) {
      let l = this.modelList[i]
      if (l.tagsSnapshot.length === 0 || !l.tagsSnapshot) {
        this.uploadError = true
        this.uploadErrorIndex = i
        this.$forceUpdate()
        this.$message({
          message: '请将新增模板填写完整!',
          type: 'error'
        })
        return
      }
      if (l.groupDiv === l.tagDiv) {
        this.$message({
          message: '组内分隔和同组分隔不可以使用相同分隔符!',
          type: 'error'
        })
        return
      }
      this.uploadError = false
      this.uploadErrorIndex = ''
      this.$refs.modelForm.validate((valid) => {
        if (valid) {
          let data = {
            id: this.modelList[i].id ? this.modelList[i].id : null,
            modelName: this.modelList[i].modelName,
            tagsSnapshot: JSON.stringify(this.modelList[i].tagsSnapshot),
            groupDiv: this.modelList[i].groupDiv,
            tagDiv: this.modelList[i].tagDiv,
            offerId: this.modelList[i].offerId,
          }
          submitModel(data).then(res => {
            if (res) {
              this.$message({
                type: 'success',
                message: '模板更新成功！',
              })
              this.onLoad({pageSize: 10, currentPage: 1, total: 0})
            }
          })
        }
      })
    },
    //添加标签
    addTags(modelIndex, modelTags) {
      if (modelIndex === 'add') {
        this.addList.tagsSnapshot = modelTags;
        this.closeDialog()
      } else {
        this.modelList[modelIndex].tagsSnapshot = modelTags;
        this.saveModel(modelIndex)
        this.closeDialog()
      }
    },
    //新增
    saveAdd() {
      let l = this.addList
      if (!l.tagsSnapshot || l.tagsSnapshot.length === 0) {
        this.addError = true
        this.$message({
          message: '请将新增模板填写完整!',
          type: 'error'
        })
        return
      }
      if (l.groupDiv === l.tagDiv) {
        this.$message({
          message: '组内分隔和同组分隔不可以使用相同分隔符!',
          type: 'error'
        })
        return
      }
      this.addError = false
      this.$refs.addList.validate((valid) => {
        if (valid) {
          let data = {
            modelName: this.addList.modelName,
            tagsSnapshot: JSON.stringify(this.addList.tagsSnapshot),
            groupDiv: this.addList.groupDiv,
            tagDiv: this.addList.tagDiv,
            offerId: this.addList.offerId,
          }
          submitModel(data).then(res => {
            if (res) {
              this.$message({
                type: 'success',
                message: '模板新增成功！',
              })
              this.page.currentPage = 1;
              this.page.total = 0;
              this.onLoad(this.page)
              this.cancelAdd()
            }
          })
        }
      })
    },
    //取消新增
    cancelAdd() {
      this.addList = {
        tagDiv: '&',
        groupDiv: '-'
      }
      this.add = false
      this.addError = false
    },
    isNamedGroup(group) {
      if (group != null) {
        if (group.type == 'system') {
          return true;
        }
        if (group.tags != null) {
          for (let i = 0; i < group.tags.length; i++) {
            if (group.tags[i].flag == 1) {
              return true;
            }
          }
        }
      }
      return false;
    },
  }
}
</script>
<style scoped lang="scss">
.add-model {
  border: 2px solid #dcdfe6;
  background: rgb(249, 249, 249);
}

.add-error-model {
  color: red;
  border: 2px solid #E74C3C !important;
  background: rgb(249, 249, 249) !important;
}

.tags-model-table {
  border: 1px solid rgba(232, 232, 232, 100);
  min-height: 35px;
  display: flex;
  padding: 3px 2em;
  text-align: center;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;

  /deep/ .el-form-item {
    margin-bottom: 0;
  }

  /deep/ .el-form-item__error {
    top: 85%;
    left: 20px;
  }
}

.tag-model-title {
  text-align: center;
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 10px;
}

.setTags {
  cursor: pointer;

  &:hover {
    color: #409eff !important;
  }
}

.systemMenu {
  font-size: 20px;
  letter-spacing: 0.3em;
  color:rgba(52, 169, 255, 100) ;
  i {
    cursor: pointer;

    &:hover {
      color: #409eff !important;
    }
  }
}

.tagsStyle {
  height: 25px;
  margin-bottom: 3px;
  padding: 0 10px;
  border-radius: 4px;
  background: white;
  font-size: 13px;
  margin-right: 5px;
  line-height: 25px;
  border: 1px solid rgba(232, 232, 232, 100);
  text-align: center;
}

.ruleDialog {
  /deep/ .el-dialog__header {
    display: none;
  }
}

.tagsRules {
  /deep/ .el-form-item__error {
    width: 280px;
    top: -29%;
    text-align: left;
  }
}

.add_set_tags {
  color: rgba(52, 169, 255, 100);
  border: 1px solid rgba(52, 169, 255, 100);
  border-radius: 5px;
  height: 27px;
  line-height: 27px;
  cursor: pointer;
  padding: 0 9px
}
</style>

